package com.uam.core.dao.mysql;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.uam.core.entity.model.AircraftModel;
import com.uam.core.entity.model.AircraftQueryResult;

import lombok.extern.slf4j.Slf4j;

@Repository
@Slf4j
public class AircraftDao {

	@Autowired
	private JdbcTemplate jdbcTemplate = null;

	private Cache<Integer, AircraftQueryResult> cache = Caffeine.newBuilder().expireAfterAccess(128, TimeUnit.MINUTES)
			.maximumSize(65536).build();

	public AircraftQueryResult detailAircraft(int id) {
		Integer wrapId = Integer.valueOf(id);
		AircraftQueryResult result = this.cache.getIfPresent(wrapId);
		if (result != null) {
			return result;
		}
		AircraftDao.log.info("---------获取飞行器详情，id:{}---------", id);
		List<AircraftModel> data = this.jdbcTemplate.query(con -> {
			PreparedStatement ps = con.prepareStatement(
					"SELECT `airplane_name`,`avg_speed`,`max_speed`,`min_altitude`,`max_altitude`,`flight_interval`,`max_endurance`,`model_name`,`safe_distance`  FROM `airplane` WHERE `airplane_id`=?");
			ps.setInt(1, id);
			return ps;
		}, new RowMapper<AircraftModel>() {

			@Override
			public AircraftModel mapRow(ResultSet rs, int rowNum) throws SQLException {
				AircraftModel aircraft = new AircraftModel();
				aircraft.setName(rs.getString("airplane_name"));
				aircraft.setSpeed(rs.getDouble("avg_speed"));
				aircraft.setMaxSpeed(rs.getDouble("max_speed"));
				aircraft.setMinAltitude(rs.getDouble("min_altitude"));
				aircraft.setMaxAltitude(rs.getDouble("max_altitude"));
				aircraft.setSafeDistance(rs.getDouble("safe_distance"));
				aircraft.setMaxDuration(rs.getInt("max_endurance"));
				aircraft.setModelName(rs.getString("model_name"));
				aircraft.setFlightInterval(rs.getDouble("flight_interval"));
				return aircraft;
			}
		});
		if (data == null || data.size() == 0) {
			result = AircraftQueryResult.EMPTY;
		} else {
			result = new AircraftQueryResult(1, data);
		}
		this.cache.put(wrapId, result);
		return result;
	}

}
